<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>显示文件上传进度</title>
</head>

<body>
  <div>
    <h1>File upload progress</h1>
    <input type="file" id="file-uploader">
    <div id="feedback"></div>
    <label id="progress-label" for="progress"></label>
    <progress id="progress" value="0" max="100"> </progress>
  </div>
</body>
<script>
  /*
  更好的可用性是让你的用户知道文件上传的进程。现在，我们知道了 FileReader 和读取和加载文件的事件。
  const reader = new FileReader();
  FileReader 有另一个事件，称为进度(progress)，知道已加载了多少。我们可以使用HTML5的 progress 标签来创建带有此信息的进度栏。

  reader.addEventListener('progress', (event) => {
  if (event.loaded && event.total) {
    // 计算完成百分比
    const percent = (event.loaded / event.total) * 100;
    // 将值设置为进度组件
    progress.value = percent;
  }
});
  */

  const fileUploader = document.getElementById('file-uploader');
  const feedback = document.getElementById('feedback');
  const progress = document.getElementById('progress');

  const reader = new FileReader();

  fileUploader.addEventListener('change', (event) => {
    const files = event.target.files;
    const file = files[0];
    reader.readAsDataURL(file);

    reader.addEventListener('progress', (event) => {
      if (event.loaded && event.total) {
        const percent = (event.loaded / event.total) * 100;
        progress.value = percent;
        document.getElementById('progress-label').innerHTML = Math.round(percent) + '%';

        if (percent === 100) {
          let msg = `<span style="color:green;">File <u><b>${file.name}</b></u> has been uploaded successfully.</span>`;
          feedback.innerHTML = msg;
        }
      }
    });
  });


</script>

</html>